# -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 00:39:42 2020

@author: xyz
"""

import json
import traceback
import picture
import sympy
import rpy2.robjects as robjects
from rpy2.robjects import globalenv, baseenv

import rpy2.robjects
from rpy2.robjects.packages import *
from rpy2.robjects.robject import *
from rpy2.robjects.vectors import *


base = importr("base")
stats = importr("stats")
nlmixr = importr("nlmixr")
RxODE = importr("RxODE")
MASS = importr("MASS")
data_table = importr("data.table")
ggforce = importr('ggforce')
ggplot2 = importr("ggplot2")
gridExtra = importr("gridExtra")
xpose = importr("xpose")
xpose_nlmixr = importr("xpose.nlmixr")
grDevices = importr("grDevices") # PDF函数的包
graphics = importr("graphics")

#base包
#设置控制台打印行数
base.options(max_print=100000)

#nlmixr包
to_fit = robjects.r.nlmixr #nlmixr的封装
tableControl = robjects.r.tableControl


#xpose.nlmixr包

#grDevices包
pdf = grDevices.pdf
dev_off = grDevices.dev_off

#graphics包
plot = graphics.plot
#必备的包
import sys
import os
from PyQt5.QtWidgets import QWidget, QApplication, QFileDialog, QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_DALTA(object):
    def setupUi(self, DALTA):
        DALTA.setObjectName("DALTA")
        DALTA.setEnabled(True)
        DALTA.resize(1440, 800)
        DALTA.setMaximumSize(QtCore.QSize(1440, 800))
        font = QtGui.QFont()
        font.setFamily("Calibri")
        font.setKerning(True)
        DALTA.setFont(font)
        DALTA.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Active, QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Active, QtGui.QIcon.On)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
        icon.addPixmap(QtGui.QPixmap(":/mainicon/DELTA.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
        DALTA.setWindowIcon(icon)
        DALTA.setStyleSheet("background-color:rgb(240, 240, 240);")
        self.leftframe = QtWidgets.QFrame(DALTA)
        self.leftframe.setGeometry(QtCore.QRect(0, 0, 250, 800))
        self.leftframe.setFrameShape(QtWidgets.QFrame.WinPanel)
        self.leftframe.setFrameShadow(QtWidgets.QFrame.Raised)
        self.leftframe.setObjectName("leftframe")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.leftframe)
        self.verticalLayout.setObjectName("verticalLayout")
        self.homepageb = QtWidgets.QPushButton(self.leftframe)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.homepageb.setFont(font)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/mainicon/首页.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.homepageb.setIcon(icon1)
        self.homepageb.setIconSize(QtCore.QSize(80, 80))
        self.homepageb.setDefault(False)
        self.homepageb.setFlat(True)
        self.homepageb.setObjectName("homepageb")
        self.verticalLayout.addWidget(self.homepageb)
        self.fitb = QtWidgets.QPushButton(self.leftframe)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.fitb.setFont(font)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/mainicon/建模.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.fitb.setIcon(icon2)
        self.fitb.setIconSize(QtCore.QSize(100, 100))
        self.fitb.setDefault(False)
        self.fitb.setFlat(True)
        self.fitb.setObjectName("fitb")
        self.verticalLayout.addWidget(self.fitb)
        self.visualb = QtWidgets.QPushButton(self.leftframe)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.visualb.setFont(font)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("可视化.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.visualb.setIcon(icon3)
        self.visualb.setIconSize(QtCore.QSize(80, 80))
        self.visualb.setFlat(True)
        self.visualb.setObjectName("visualb")
        self.verticalLayout.addWidget(self.visualb)
        self.checkb = QtWidgets.QPushButton(self.leftframe)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.checkb.setFont(font)
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap(":/mainicon/诊断.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.checkb.setIcon(icon4)
        self.checkb.setIconSize(QtCore.QSize(100, 100))
        self.checkb.setFlat(True)
        self.checkb.setObjectName("checkb")
        self.verticalLayout.addWidget(self.checkb)
        self.medicineb = QtWidgets.QPushButton(self.leftframe)
        font = QtGui.QFont()
        font.setPointSize(11)
        self.medicineb.setFont(font)
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap(":/mainicon/方案.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.medicineb.setIcon(icon5)
        self.medicineb.setIconSize(QtCore.QSize(110, 90))
        self.medicineb.setFlat(True)
        self.medicineb.setObjectName("medicineb")
        self.verticalLayout.addWidget(self.medicineb)
        self.check = QtWidgets.QFrame(DALTA)
        self.check.setGeometry(QtCore.QRect(250, 0, 1190, 800))
        self.check.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.check.setFrameShadow(QtWidgets.QFrame.Raised)
        self.check.setObjectName("check")
        self.label_7 = QtWidgets.QLabel(self.check)
        self.label_7.setGeometry(QtCore.QRect(50, 50, 421, 41))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.check)
        self.lineEdit_2.setGeometry(QtCore.QRect(310, 430, 351, 31))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.label_9 = QtWidgets.QLabel(self.check)
        self.label_9.setGeometry(QtCore.QRect(310, 390, 271, 31))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        font.setKerning(True)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.textBrowser_2 = QtWidgets.QTextBrowser(self.check)
        self.textBrowser_2.setGeometry(QtCore.QRect(310, 230, 421, 141))
        self.textBrowser_2.setObjectName("textBrowser_2")
        self.label_10 = QtWidgets.QLabel(self.check)
        self.label_10.setGeometry(QtCore.QRect(311, 480, 231, 41))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label_10.setFont(font)
        self.label_10.setObjectName("label_10")
        self.pushButton_4 = QtWidgets.QPushButton(self.check)
        self.pushButton_4.setGeometry(QtCore.QRect(671, 430, 112, 31))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_5 = QtWidgets.QPushButton(self.check)
        self.pushButton_5.setGeometry(QtCore.QRect(310, 180, 271, 34))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_6 = QtWidgets.QPushButton(self.check)
        self.pushButton_6.setGeometry(QtCore.QRect(530, 620, 112, 34))
        self.pushButton_6.setObjectName("pushButton_6")
        self.obs_dv = QtWidgets.QCheckBox(self.check)
        self.obs_dv.setGeometry(QtCore.QRect(312, 530, 110, 22))
        self.obs_dv.setObjectName("obs_dv")
        self.medicine = QtWidgets.QFrame(DALTA)
        self.medicine.setGeometry(QtCore.QRect(250, 0, 1190, 800))
        self.medicine.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.medicine.setFrameShadow(QtWidgets.QFrame.Raised)
        self.medicine.setObjectName("medicine")
        self.label_8 = QtWidgets.QLabel(self.medicine)
        self.label_8.setGeometry(QtCore.QRect(50, 50, 421, 41))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")
        self.textBrowser_3 = QtWidgets.QTextBrowser(self.medicine)
        self.textBrowser_3.setGeometry(QtCore.QRect(300, 230, 421, 221))
        self.textBrowser_3.setObjectName("textBrowser_3")
        self.pushButton_7 = QtWidgets.QPushButton(self.medicine)
        self.pushButton_7.setGeometry(QtCore.QRect(300, 180, 271, 34))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.pushButton_7.setFont(font)
        self.pushButton_7.setObjectName("pushButton_7")
        self.pushButton_8 = QtWidgets.QPushButton(self.medicine)
        self.pushButton_8.setGeometry(QtCore.QRect(530, 620, 112, 34))
        self.pushButton_8.setObjectName("pushButton_8")
        self.label_11 = QtWidgets.QLabel(self.medicine)
        self.label_11.setGeometry(QtCore.QRect(300, 480, 271, 31))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        font.setKerning(True)
        self.label_11.setFont(font)
        self.label_11.setObjectName("label_11")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.medicine)
        self.lineEdit_3.setGeometry(QtCore.QRect(300, 520, 351, 31))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.pushButton_9 = QtWidgets.QPushButton(self.medicine)
        self.pushButton_9.setGeometry(QtCore.QRect(661, 520, 112, 31))
        self.pushButton_9.setObjectName("pushButton_9")
        self.fit = QtWidgets.QFrame(DALTA)
        self.fit.setGeometry(QtCore.QRect(250, 0, 1190, 800))
        self.fit.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.fit.setFrameShadow(QtWidgets.QFrame.Raised)
        self.fit.setObjectName("fit")
        self.label_1 = QtWidgets.QLabel(self.fit)
        self.label_1.setGeometry(QtCore.QRect(50, 40, 391, 71))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label_1.setFont(font)
        self.label_1.setObjectName("label_1")
        self.beginb = QtWidgets.QPushButton(self.fit)
        self.beginb.setGeometry(QtCore.QRect(530, 620, 110, 35))
        self.beginb.setObjectName("beginb")
        self.label_4 = QtWidgets.QLabel(self.fit)
        self.label_4.setGeometry(QtCore.QRect(370, 480, 88, 24))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_2 = QtWidgets.QLabel(self.fit)
        self.label_2.setGeometry(QtCore.QRect(370, 200, 88, 24))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.pb = QtWidgets.QLineEdit(self.fit)
        self.pb.setGeometry(QtCore.QRect(520, 200, 251, 25))
        self.pb.setObjectName("pb")
        self.tb = QtWidgets.QToolButton(self.fit)
        self.tb.setGeometry(QtCore.QRect(770, 200, 52, 24))
        self.tb.setObjectName("tb")
        self.label_3 = QtWidgets.QLabel(self.fit)
        self.label_3.setGeometry(QtCore.QRect(370, 340, 88, 24))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.ode_ab = QtWidgets.QPushButton(self.fit)
        self.ode_ab.setGeometry(QtCore.QRect(520, 332, 155, 35))
        self.ode_ab.setObjectName("ode_ab")
        self.choose = QtWidgets.QComboBox(self.fit)
        self.choose.addItems([' ','nlme','saem','focei'])
        self.choose.setGeometry(QtCore.QRect(520, 480, 155, 35))
        self.choose.setObjectName("choose")
        self.visual = QtWidgets.QFrame(DALTA)
        self.visual.setGeometry(QtCore.QRect(250, 0, 1190, 800))
        self.visual.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.visual.setFrameShadow(QtWidgets.QFrame.Raised)
        self.visual.setObjectName("visual")
        self.label_5 = QtWidgets.QLabel(self.visual)
        self.label_5.setGeometry(QtCore.QRect(50, 50, 421, 41))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.label = QtWidgets.QLabel(self.visual)
        self.label.setGeometry(QtCore.QRect(310, 470, 231, 41))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.visual)
        self.pushButton.setGeometry(QtCore.QRect(530, 620, 112, 34))
        self.pushButton.setObjectName("pushButton")
        self.res_vs_pred = QtWidgets.QCheckBox(self.visual)
        self.res_vs_pred.setGeometry(QtCore.QRect(620, 560, 121, 26))
        self.res_vs_pred.setObjectName("res_vs_pred")
        self.dv_vs_ipred = QtWidgets.QCheckBox(self.visual)
        self.dv_vs_ipred.setGeometry(QtCore.QRect(620, 520, 120, 26))
        self.dv_vs_ipred.setObjectName("dv_vs_ipred")
        self.res_vs_idv = QtWidgets.QCheckBox(self.visual)
        self.res_vs_idv.setGeometry(QtCore.QRect(311, 566, 109, 26))
        self.res_vs_idv.setObjectName("res_vs_idv")
        self.dv_vs_pred = QtWidgets.QCheckBox(self.visual)
        self.dv_vs_pred.setGeometry(QtCore.QRect(311, 520, 116, 26))
        self.dv_vs_pred.setCheckable(True)
        self.dv_vs_pred.setTristate(False)
        self.dv_vs_pred.setObjectName("dv_vs_pred")
        self.pushButton_2 = QtWidgets.QPushButton(self.visual)
        self.pushButton_2.setGeometry(QtCore.QRect(309, 180, 271, 34))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.textBrowser = QtWidgets.QTextBrowser(self.visual)
        self.textBrowser.setGeometry(QtCore.QRect(309, 230, 421, 141))
        self.textBrowser.setObjectName("textBrowser")
        self.label_6 = QtWidgets.QLabel(self.visual)
        self.label_6.setGeometry(QtCore.QRect(309, 390, 271, 31))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(9)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.lineEdit = QtWidgets.QLineEdit(self.visual)
        self.lineEdit.setGeometry(QtCore.QRect(309, 430, 351, 31))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton_3 = QtWidgets.QPushButton(self.visual)
        self.pushButton_3.setGeometry(QtCore.QRect(670, 430, 112, 31))
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_5.raise_()
        self.label.raise_()
        self.pushButton.raise_()
        self.res_vs_pred.raise_()
        self.res_vs_idv.raise_()
        self.dv_vs_pred.raise_()
        self.pushButton_2.raise_()
        self.textBrowser.raise_()
        self.label_6.raise_()
        self.lineEdit.raise_()
        self.pushButton_3.raise_()
        self.dv_vs_ipred.raise_()
        self.homepage = QtWidgets.QFrame(DALTA)
        self.homepage.setGeometry(QtCore.QRect(250, 0, 1190, 800))
        self.homepage.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.homepage.setFrameShadow(QtWidgets.QFrame.Raised)
        self.homepage.setObjectName("homepage")
        self.textBrowser_4 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_4.setGeometry(QtCore.QRect(110, 270, 441, 151))
        self.textBrowser_4.setAutoFillBackground(False)
        self.textBrowser_4.setFrameShape(QtWidgets.QFrame.Box)
        self.textBrowser_4.setFrameShadow(QtWidgets.QFrame.Plain)
        self.textBrowser_4.setTabChangesFocus(False)
        self.textBrowser_4.setObjectName("textBrowser_4")
        self.textBrowser_5 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_5.setGeometry(QtCore.QRect(600, 270, 441, 151))
        self.textBrowser_5.setFrameShape(QtWidgets.QFrame.Box)
        self.textBrowser_5.setFrameShadow(QtWidgets.QFrame.Plain)
        self.textBrowser_5.setObjectName("textBrowser_5")
        self.textBrowser_6 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_6.setGeometry(QtCore.QRect(110, 440, 441, 151))
        self.textBrowser_6.setFrameShape(QtWidgets.QFrame.Box)
        self.textBrowser_6.setFrameShadow(QtWidgets.QFrame.Plain)
        self.textBrowser_6.setObjectName("textBrowser_6")
        self.textBrowser_7 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_7.setGeometry(QtCore.QRect(600, 440, 441, 151))
        self.textBrowser_7.setFrameShape(QtWidgets.QFrame.Box)
        self.textBrowser_7.setFrameShadow(QtWidgets.QFrame.Plain)
        self.textBrowser_7.setObjectName("textBrowser_7")
        self.textBrowser_8 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_8.setGeometry(QtCore.QRect(50, 620, 781, 121))
        self.textBrowser_8.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.textBrowser_8.setObjectName("textBrowser_8")
        self.textBrowser_9 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_9.setGeometry(QtCore.QRect(940, 710, 261, 101))
        self.textBrowser_9.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.textBrowser_9.setObjectName("textBrowser_9")
        self.textBrowser_10 = QtWidgets.QTextBrowser(self.homepage)
        self.textBrowser_10.setGeometry(QtCore.QRect(110, 60, 931, 201))
        self.textBrowser_10.setAutoFillBackground(False)
        self.textBrowser_10.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.textBrowser_10.setFrameShadow(QtWidgets.QFrame.Plain)
        self.textBrowser_10.setTabChangesFocus(False)
        self.textBrowser_10.setObjectName("textBrowser_10")
        self.leftframe.raise_()
        self.fit.raise_()
        self.check.raise_()
        self.visual.raise_()
        self.medicine.raise_()
        self.homepage.raise_()

        self.retranslateUi(DALTA)
        QtCore.QMetaObject.connectSlotsByName(DALTA)

    def retranslateUi(self, DALTA):
        _translate = QtCore.QCoreApplication.translate
        DALTA.setWindowTitle(_translate("DALTA", "DELTA"))
        self.homepageb.setText(_translate("DALTA", "  主页  "))
        self.fitb.setText(_translate("DALTA", "模型拟合"))
        self.visualb.setText(_translate("DALTA", "  数据图表"))
        self.checkb.setText(_translate("DALTA", " 模型诊断"))
        self.medicineb.setText(_translate("DALTA", "  给药方案"))
        self.label_7.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">对模型进行评估</p></body></html>"))
        self.lineEdit_2.setPlaceholderText(_translate("DALTA", "请输入上方以 fit 开头的对象"))
        self.label_9.setText(_translate("DALTA", "在下方输入拟合数据的名称"))
        self.label_10.setText(_translate("DALTA", "请选择需要查看的数据"))
        self.pushButton_4.setText(_translate("DALTA", "确定"))
        self.pushButton_5.setText(_translate("DALTA", "点击显示当前环境下的所有变量"))
        self.pushButton_6.setText(_translate("DALTA", "开始"))
        self.obs_dv.setText(_translate("DALTA", "obs_dv"))
        self.label_8.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">给药方案设计</p></body></html>"))
        self.pushButton_7.setText(_translate("DALTA", "点击显示当前环境下的所有变量"))
        self.pushButton_8.setText(_translate("DALTA", "开始"))
        self.label_11.setText(_translate("DALTA", "在下方输入拟合数据的名称"))
        self.lineEdit_3.setPlaceholderText(_translate("DALTA", "请输入上方以 fit 开头的对象"))
        self.pushButton_9.setText(_translate("DALTA", "确定"))
        self.label_1.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">在此进行数据拟合</p></body></html>"))
        self.beginb.setText(_translate("DALTA", "开始"))
        self.label_4.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">选择算法</p></body></html>"))
        self.label_2.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">导入数据</p></body></html>"))
        self.pb.setPlaceholderText(_translate("DALTA", "请点击后方按钮选择文件"))
        self.tb.setText(_translate("DALTA", "..."))
        self.label_3.setText(_translate("DALTA", "<html><head/><body><p align=\"center\"><span style=\" color:#000000;\">创建模型</span></p></body></html>"))
        self.ode_ab.setText(_translate("DALTA", "设置微分方程"))
        self.label_5.setText(_translate("DALTA", "<html><head/><body><p align=\"center\">对拟合数据进行可视化</p></body></html>"))
        self.label.setText(_translate("DALTA", "请选择需要查看的数据"))
        self.pushButton.setText(_translate("DALTA", "开始"))
        self.res_vs_pred.setText(_translate("DALTA", "res_vs_pred"))
        self.dv_vs_ipred.setText(_translate("DALTA", "dv_vs_ipred"))
        self.res_vs_idv.setText(_translate("DALTA", "res_vs_idv"))
        self.dv_vs_pred.setText(_translate("DALTA", "dv_vs_pred"))
        self.pushButton_2.setText(_translate("DALTA", "点击显示当前环境下的所有变量"))
        self.label_6.setText(_translate("DALTA", "在下方输入拟合数据的名称"))
        self.lineEdit.setPlaceholderText(_translate("DALTA", "请输入上方以 fit 开头的对象"))
        self.pushButton_3.setText(_translate("DALTA", "确定"))
        self.textBrowser_4.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600;\">模型拟合模块使用步骤</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. 在导入数据一栏，点击…按钮选择本地数据集。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. 在创建模型一栏，点击“设置微分方程”，在弹出的窗口中依次设置模型的名称，模型的参数，模型的微分方程。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. 在选择算法一栏，提供nlme,saem,focei三种算法供选择。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4，上述步骤完成后点击最下方的“开始”按钮即可开始运行，因数据量和设备的不同，等待时间约为5分钟以上。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. 数据生成完毕后，界面将会显示生成的数据，点击界面下方的“保存”按钮，即可将数据保存在软件的安装目录中。</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))
        self.textBrowser_5.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600;\">数据图表模块使用步骤</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. 首先点击“点击显示当前环境下的所有变量”按钮，即可在下方获取所有的变量。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. 找到以fit开头的数据，该数据即上一模块生成的数据。（fit后方的文字为上一模块设置的模型的名称）</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. 将该数据的名称输入到下方文本框中，输入完毕后，点击右侧的确定按钮，上传数据。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. 本模块提供了4重可供查看的数据可视化图标，勾选想要查看的类型即可。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. 点击开始，开始生成图表，此过程因配置可能需要几分钟，完成后会有弹窗提醒。</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))
        self.textBrowser_6.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600;\">模型诊断模块使用步骤</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. 首先点击“点击显示当前环境下的所有变量”按钮，即可在下方获取所有的变量。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. 找到以fit开头的数据，该数据即模型拟合模块生成的数据。（fit后方的文字为模型模块设置的模型的名称）</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. 将该数据的名称输入到下方文本框中，输入完毕后，点击右侧的确定按钮，上传数据。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. 本模块提供了1中可供查看的图表，勾选想要查看的类型即可。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">5. 点击开始，开始生成图表，此过程因配置可能需要几分钟，完成后会有弹窗提醒。</p></body></html>"))
        self.textBrowser_7.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600;\">给药方案模块使用步骤</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1. 首先点击“点击显示当前环境下的所有变量”按钮，即可在下方获取所有的变量。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">2. 找到以fit开头的数据，该数据即模型拟合模块生成的数据。（fit后方的文字为模型模块设置的模型的名称）</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">3. 将该数据的名称输入到下方文本框中，输入完毕后，点击右侧的确定按钮，上传数据，完成后会有弹窗提醒。</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">4. 点击开始，开始生成图表，此过程因配置可能需要几分钟，完成后会有弹窗提醒。</p></body></html>"))
        self.textBrowser_8.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:11pt; font-weight:600; color:#d83c2d;\">DELTA GROUP</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:17pt; font-weight:600; color:#d83c2d;\">   </span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:8pt; font-weight:600; color:#252527;\">Nanjing, China</span><span style=\" font-family:\'Calibri\'; font-size:8pt;\"> </span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#d83c2d;\">D</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">rug </span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#d83c2d;\">E</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">fficiency </span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#d83c2d;\">L</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">earning </span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#d83c2d;\">T</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">ools and </span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#d83c2d;\">A</span><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">pplications</span><span style=\" font-family:\'Calibri\';\"> </span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; color:#252527;\">Contact with: tpang@cpu.edu.cn (Prof. Tao Pang); jansen@njupt.edu.cn (Prof. Jiansheng Wu)</span><span style=\" font-family:\'Calibri\';\"> </span></p></body></html>"))
        self.textBrowser_9.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:8pt; color:#4a4a4e;\">Designed by </span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:8pt; color:#4a4a4e;\">Calvin Ju(645207591@qq.com),</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:8pt; color:#4a4a4e;\">Lvy(529221498@qq.com) and </span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Franklin Gothic Medium,sans-serif\'; font-size:8pt; color:#4a4a4e;\">Klayoe.J(1012315603@qq.com)</span></p></body></html>"))
        self.textBrowser_10.setHtml(_translate("DALTA", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:11pt; font-weight:600;\">软件简介</span></p>\n"
"<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:11pt; font-weight:600;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:11pt;\">    这是一款针对群体PKPD建模的软件，用于拟合一般动力学模型，特别是药代动力学（PK）模型和药代动力学-药效动力学（PKPD）模型。该软件主要功能有：模型拟合、数据图表、模型诊断和给药方案。PK即药物代谢动力学，研究药物在体内的吸收分布处置代谢，PD即药物效应动力学，研究药物对机体的作用及规律，PKPD即研究血药浓度-时间-药物效应三者间关系的学科。</span></p></body></html>"))

class Ui_OdeAWin(object):
    def setupUi(self, OdeAWin):
        OdeAWin.setObjectName("OdeAWin")
        OdeAWin.resize(1042, 644)
        self.layoutWidget = QtWidgets.QWidget(OdeAWin)
        self.layoutWidget.setGeometry(QtCore.QRect(390, 580, 242, 36))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.okb = QtWidgets.QPushButton(self.layoutWidget)
        self.okb.setObjectName("okb")
        self.horizontalLayout.addWidget(self.okb)
        self.cb = QtWidgets.QPushButton(self.layoutWidget)
        self.cb.setObjectName("cb")
        self.horizontalLayout.addWidget(self.cb)
        self.modelformula = QtWidgets.QPlainTextEdit(OdeAWin)
        self.modelformula.setGeometry(QtCore.QRect(100, 320, 851, 201))
        self.modelformula.setPlainText("")
        self.modelformula.setObjectName("modelformula")
        self.modelsetting = QtWidgets.QPlainTextEdit(OdeAWin)
        self.modelsetting.setGeometry(QtCore.QRect(100, 90, 851, 201))
        self.modelsetting.setPlainText("")
        self.modelsetting.setObjectName("modelsetting")
        self.modelname = QtWidgets.QLineEdit(OdeAWin)
        self.modelname.setGeometry(QtCore.QRect(100, 30, 851, 31))
        self.modelname.setObjectName("modelname")

        self.retranslateUi(OdeAWin)
        QtCore.QMetaObject.connectSlotsByName(OdeAWin)

    def retranslateUi(self, OdeAWin):
        _translate = QtCore.QCoreApplication.translate
        OdeAWin.setWindowTitle(_translate("OdeAWin", "DELTA"))
        self.okb.setText(_translate("OdeAWin", "确定"))
        self.cb.setText(_translate("OdeAWin", "取消"))
        self.modelformula.setPlaceholderText(_translate("OdeAWin", "请在此设置微分方程..."))
        self.modelsetting.setPlaceholderText(_translate("OdeAWin", "请在此输入模型参数..."))
        self.modelname.setPlaceholderText(_translate("OdeAWin", "请输入需要创建的模型名称..."))

class Ui_fitresult(object):
    
    def setupUi(self, fitresult):
        fitresult.setObjectName("fitresult")
        fitresult.resize(1012, 692)
        self.text = QtWidgets.QTextBrowser(fitresult)
        self.text.setGeometry(QtCore.QRect(60, 30, 891, 541))
        self.text.setObjectName("text")
        self.layoutWidget = QtWidgets.QWidget(fitresult)
        self.layoutWidget.setGeometry(QtCore.QRect(380, 620, 242, 36))
        self.layoutWidget.setObjectName("layoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.sb = QtWidgets.QPushButton(self.layoutWidget)
        self.sb.setEnabled(True)
        self.sb.setObjectName("sb")
        self.horizontalLayout.addWidget(self.sb)
        self.cb = QtWidgets.QPushButton(self.layoutWidget)
        self.cb.setObjectName("cb")
        self.horizontalLayout.addWidget(self.cb)

        self.retranslateUi(fitresult)
        QtCore.QMetaObject.connectSlotsByName(fitresult)

    def retranslateUi(self, fitresult):
        _translate = QtCore.QCoreApplication.translate
        fitresult.setWindowTitle(_translate("fitresult", "DELTA"))
        self.text.setPlaceholderText(_translate("fitresult", "正在拟合数据请稍后...拟合完成后将在此页面显示最终结果...                                        为了保证程序的顺利运行，拟合期间请勿操作其他功能..."))
        self.sb.setText(_translate("fitresult", "保存"))
        self.cb.setText(_translate("fitresult", "取消"))

class MainWin(QWidget, Ui_DALTA):
    
    #定义了主窗口的控件，和点击左侧按钮切换界面的函数
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.fit.hide()
        self.visual.hide()
        self.check.hide()
        self.medicine.hide()
        #左侧四个按钮点击进行界面切换
        self.fitb.clicked.connect(lambda: self.indicator(1))
        self.visualb.clicked.connect(lambda: self.indicator(2))
        self.checkb.clicked.connect(lambda: self.indicator(3))
        self.medicineb.clicked.connect(lambda: self.indicator(4))
        self.homepageb.clicked.connect(lambda: self.indicator(5))
        
        
    def indicator(self,num):
        #用来指定显示哪一个界面
            self.homepage.hide()
            self.fit.hide()
            self.visual.hide()
            self.check.hide()
            self.medicine.hide()
            if num == 1:
                self.fit.show()
            if num == 2 :
                self.visual.show()
            if num ==3 :
                self.check.show()
            if num == 4:
                self.medicine.show()
            if num == 5:
                self.homepage.show()

class OdeAwin(QWidget, Ui_OdeAWin):
    # 手动创建模型的子窗口
    def __init__(self):
        super().__init__()
        self.setupUi(self)

class FitResultWin(QWidget, Ui_fitresult):
    # 显示数据结果的窗口
    def __init__(self):
        super().__init__()
        self.setupUi(self)
    
        
class Fit(MainWin):
    def __init__(self):
        super().__init__()  
        #创建一个手动构建模型的子窗口
        self.ode_a = OdeAwin()
        #创建一个显示数据结果的窗口
        self.fit_result = FitResultWin()
        #点击加载数据的按钮加载数据
        self.tb.clicked.connect(self.openfile)
        self.tb.clicked.connect(self.loadfile)
        #打开手动构建模型的子窗口
        self.ode_ab.clicked.connect(self.show_ode_a)
        #在窗口中获取模型参数并创建，创建完成后关闭
        self.ode_a.okb.clicked.connect(self.create_it)
        self.ode_a.cb.clicked.connect(self.ode_a.close)
        #选择算法，返回算法名称
        self.choose.currentIndexChanged.connect(self.choose_it)
        #开始拟合数据
        self.beginb.clicked.connect(self.show_fit_result)
        self.beginb.clicked.connect(self.fit_it)
        #显示拟合数据的表格
        self.fit_result.sb.clicked.connect(self.display_fit_data)
        self.fit_result.sb.clicked.connect(self.fit_result.close)
        self.fit_result.sb.clicked.connect(self.clean_fit_result)
        #关闭拟合数据窗口
        self.fit_result.cb.clicked.connect(self.fit_result.close)
        self.fit_result.cb.clicked.connect(self.clean_fit_result)
    
    def show_ode_a(self):
        #显示手动创建模型的子窗口
        self.ode_a.show()
        
    def show_ode_b(self):
        #显示自动创建模型的子窗口
        pass
    
    def show_fit_result(self):
        self.fit_result.show()
        
    def openfile(self):
        #打开文件
        self.fname = QFileDialog.getOpenFileName(self,'请选择文件','','*')
    
    def loadfile(self):
        #用按钮读取文件
        try:
            self.pb.setText(self.fname[0])
            data_path = self.fname[0]
            data_path = data_path.replace('/','\\''\\')
            self.data = robjects.r('''read.csv("%s", na.strings=c("."))''' %data_path)
            #在R环境里创建一个dataset
            fname_in_global = self.fname[0].split('/') #将路径分成以\\隔开的列表
            robjects.globalenv['%s'%fname_in_global[-1]] = self.data
            QMessageBox.information(self,'提示','数据上传成功！',QMessageBox.Ok,QMessageBox.Ok)
        except:
            pass

    def create_it(self):
        #创建模型
        self.modelname = self.ode_a.modelname.text()
        #修改格式函数
        def add_space(num, list):
            l = []
            for x in list:
                x = num * ' ' + x
                l.append(x)
            return l
        modelsetting = self.ode_a.modelsetting.toPlainText()
        modelsetting = modelsetting.strip().split('\n')
        modelsetting = add_space(4,modelsetting)
        self.modelsetting = '\n'.join(modelsetting)
        # print(self.modelsetting)
        
        modelformula = self.ode_a.modelformula.toPlainText()
        modelformula = modelformula.strip().split('\n')
        modelformula = add_space(4,modelformula)
        self.modelformula = '\n'.join(modelformula)
        # print(self.modelformula)
        
        model = '''%s <- function() {
  ini({
%s
  })
  model({
%s
  })
}'''%(self.modelname, self.modelsetting, self.modelformula)
        # print(model)
        try:
            self.model = robjects.r('''%s''' %model)
        except:
            QMessageBox.critical(self,'提示','模型创建失败,请检查输入内容是否正确!',QMessageBox.Ok,QMessageBox.Ok)
        # print(self.model)
        else:
            QMessageBox.information(self,'提示','模型创建成功！',QMessageBox.Ok,QMessageBox.Ok)
            self.ode_a.modelname.setText('')
            self.ode_a.modelsetting.clear()
            self.ode_a.modelformula.clear()
            self.ode_a.close()

    def choose_it(self):
        #选择算法时候饭后算法名称
        self.algo = self.choose.currentText()

    def fit_it(self):
        #给函数的参数赋值
        self.beginb.setEnabled(False)
        model = self.model
        data = self.data
        algo = self.algo
        # algo = str(algo)
        print("everything ok!")
        self.result = to_fit(model, data, algo, table=tableControl(cwres=True, npde=True))
        robjects.globalenv['fit.'+self.modelname] = self.result
        # print(result)
        #把数据保存到本地output.txt文本中
        f = open(r'output.txt','w+')
        print(self.result,file=f)
        f.close()  
        #读取本地文本
        f = open('output.txt','r')
        contents = f.read()
        self.fit_result.text.setText(contents)
        self.beginb.setEnabled(True)
        #删除本地文本缓存
        # os.remove('output.txt')
    
    def display_fit_data(self):
        self.display_fit_data = robjects.r('''write.csv(%s, file="%s", quote = F, na = ".", row.names = F)''' %('fit.'+self.modelname,'fit.'+self.modelname+'.csv'))
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)
    
    def clean_fit_result(self):
        self.fit_result.text.setText('')
    
class VisualPlot(MainWin):
    def __init__(self):
        super().__init__()
        self.plot_list_in_visual = []
        #获取globalenv的按钮
        self.pushButton_2.clicked.connect(self.get_globalenv_in_visual)
        self.pushButton_2.clicked.connect(self.display_globalenv_in_visual)
        #获取选中变量的按钮 self.global_var_in_visual是最终返回的被选中的var
        self.pushButton_3.clicked.connect(self.get_contents_in_lineEdit)
        #选中某个功能
        self.dv_vs_pred.stateChanged.connect(self.choose_dv_vs_pred)
        self.dv_vs_ipred.stateChanged.connect(self.choose_dv_vs_ipred)
        self.res_vs_idv.stateChanged.connect(self.choose_res_vs_idv)
        self.res_vs_pred.stateChanged.connect(self.choose_res_vs_pred)
        #作图
        self.pushButton.clicked.connect(self.plot_it_in_visual)
        
    def get_globalenv_in_visual(self):
        #获取globalenv中的变量
        glonames = robjects.r.ls(globalenv)
        self.globalnames = []
        for x in glonames:
            self.globalnames.append(x)
        
    def display_globalenv_in_visual(self):
        #显示globalenv中的变量
        self.textBrowser.setText('')
        for x in self.globalnames:
            self.textBrowser.append(x)
    
    def get_contents_in_lineEdit(self):
        #获取从lineEdit输入的内容
        self.global_var_in_visual = self.lineEdit.text()
        # print(type(self.global_var_in_visual))
        QMessageBox.information(self,'提示','获取成功！',QMessageBox.Ok,QMessageBox.Ok)
        return self.global_var_in_visual

    def choose_dv_vs_pred(self, state):
        #当选择了dv_vs_pred按钮，将dv_vs_pred添加到需要绘制图表的列表里
        if state == Qt.Checked:
            self.plot_list_in_visual.append('dv_vs_pred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('dv_vs_pred')
            # print(self.plot_list_in_visual)
            
    def choose_dv_vs_ipred(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('dv_vs_ipred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('dv_vs_ipred')
            # print(self.plot_list_in_visual)
            
    def choose_res_vs_idv(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('res_vs_idv')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('res_vs_idv')
            # print(self.plot_list_in_visual)
            
    def choose_res_vs_pred(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('res_vs_pred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('res_vs_pred')
            # print(self.plot_list_in_visual)
    
    def plot_it_in_visual(self):
        self.pushButton.setEnabled(False)
        #用visual界面绘图
        l = []
        robjects.r('''xp.%s <- xpose_data_nlmixr(%s, xp_theme = theme_xp_nlmixr())''' %(self.global_var_in_visual,self.global_var_in_visual))
        if 'dv_vs_pred' in self.plot_list_in_visual:
             xp1 = robjects.r('''xp1 <- dv_vs_pred(xp.%s, title = "DV vs PRED",
                   subtitle = NULL, caption = NULL) +
   coord_cartesian(ylim=c(0,1000), xlim=c(0,1000)) +
   scale_x_continuous("Population predictions") +
   scale_y_continuous("Observed concentrations")''' %self.global_var_in_visual)
             l.append('xp1,')
        else:
            l.append('')
  
        if 'dv_vs_ipred' in self.plot_list_in_visual:
            xp2 = robjects.r('''xp2 <- dv_vs_ipred(xp.%s, title = "DV vs IPRED",
                   subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(0,1000), xlim=c(0,1000))+
  scale_x_continuous("Individual predictions") +
  scale_y_continuous("Observed concentrations")''' %self.global_var_in_visual)
            l.append('xp2,')
        else:
            l.append('')
  
        if 'res_vs_idv' in self.plot_list_in_visual:
            xp3 = robjects.r('''xp3 <- res_vs_idv(xp.%s, res = "CWRES", title = "CWRES vs time",
                  subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(-3.5,3.5)) +
  scale_x_continuous("Time (h)") +
  scale_y_continuous("Conditional weighted residuals")''' %self.global_var_in_visual)
            l.append('xp3,')
        else:
            l.append('')
  
        if 'res_vs_pred' in self.plot_list_in_visual:
            xp4 = robjects.r('''xp4 <- res_vs_idv(xp.%s, res = "CWRES", title = "CWRES vs time",
                  subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(-3.5,3.5)) +
  scale_x_continuous("Time (h)") +
  scale_y_continuous("Conditional weighted residuals")''' %self.global_var_in_visual)
            l.append('xp4,')
        else:
            l.append('')

        #将xp1至xp4绘制在一个pdf中
        pdf("fig1_%s.pdf" %self.global_var_in_visual ,width=8,height=8)
        robjects.r('''grid.arrange(%s%s%s%s nrow=2)'''%(l[0],l[1],l[2],l[3]))
        dev_off()
        self.pushButton.setEnabled(True)
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)

class CheckVpc(MainWin):
    def __init__(self):
        super().__init__()
        #用来存放需要绘制图形的变量名称
        self.plot_list_in_check = [] 
        #获取globalenv的按钮
        self.pushButton_5.clicked.connect(self.get_globalenv_in_check)
        self.pushButton_5.clicked.connect(self.display_globalenv_in_check)
        #获取选中变量的按钮 self.global_var_in_check是最终返回的被选中的var
        self.pushButton_4.clicked.connect(self.get_contents_in_lineEdit_2)
        #选中某个功能
        self.obs_dv.stateChanged.connect(self.choose_obs_dv)
        #生成pdf
        self.pushButton_6.clicked.connect(self.wait_three_minute)
        self.pushButton_6.clicked.connect(self.plot_it_in_check)
    
    def get_globalenv_in_check(self):
        #获取globalenv中的变量
        glonames = robjects.r.ls(globalenv)
        self.globalnames = []
        for x in glonames:
            self.globalnames.append(x)
            
    def display_globalenv_in_check(self):
        #显示globalenv中的变量
        self.textBrowser_2.setText('')
        for x in self.globalnames:
            self.textBrowser_2.append(x)
    
    def get_contents_in_lineEdit_2(self):
        #获取从lineEdit_2的输入的内容
        self.global_var_in_check = self.lineEdit_2.text()
        # print(type(self.global_var_in_check))
        QMessageBox.information(self,'提示','获取成功！',QMessageBox.Ok,QMessageBox.Ok)
        return self.global_var_in_check

    def choose_obs_dv(self,state):
        #当选择了obs_dv
        if state == Qt.Checked:
            self.plot_list_in_check.append('obs_dv')
        else:
            self.plot_list_in_check.remove('obs_dv')
    
    def wait_three_minute(self):
        QMessageBox.information(self,'提示','此过程大概需要三分钟',QMessageBox.Ok,QMessageBox.Ok)
        
    def plot_it_in_check(self):
        #作图
        self.pushButton_6.setEnabled(False)
        l = []
        robjects.r('''bins <- c(0, 3, 12, 24, 168, 171, 180, 192)''')
        robjects.r('''vpc.%s <- nlmixr::vpc(%s, nsim=700,show=list(obs_dv=T),
                   bins=bins)''' %(self.global_var_in_check,self.global_var_in_check))
        
        if 'obs_dv' in self.plot_list_in_check:
            vpc1 = robjects.r('''vpc1 = vpc.%s$gg +
      scale_x_continuous("Time (h)") +
        scale_y_continuous("Concentration")'''%self.global_var_in_check)
            l.append('vpc1,')
        else:
            l.append('')
        #保存图片
        pdf("fig2_%s.pdf" %self.global_var_in_check ,width=8,height=8)
        robjects.r('''grid.arrange(%s nrow=2)'''%(l[0]))
        dev_off()
        self.pushButton_6.setEnabled(True)
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)
        
class MedicinePlot(MainWin):
    def __init__(self):
        super().__init__()
        #用来存放需要绘制图形的变量名称
        self.plot_list_in_medicine = [] 
        #获取globalenv的按钮
        self.pushButton_7.clicked.connect(self.get_globalenv_in_medicine)
        self.pushButton_7.clicked.connect(self.display_globalenv_in_medicine)
        #获取选中变量的按钮 self.global_var_in_check是最终返回的被选中的var
        self.pushButton_9.clicked.connect(self.get_contents_in_lineEdit_3)
        #生成pdf
        self.pushButton_8.clicked.connect(self.wait_three_minute)
        self.pushButton_8.clicked.connect(self.plot_it_in_medicine)
        
    def get_globalenv_in_medicine(self):
        #获取globalenv中的变量
        glonames = robjects.r.ls(globalenv)
        self.globalnames = []
        for x in glonames:
            self.globalnames.append(x)
            
    def display_globalenv_in_medicine(self):
        #显示globalenv中的变量
        self.textBrowser_3.setText('')
        for x in self.globalnames:
            self.textBrowser_3.append(x)
            
    def get_contents_in_lineEdit_3(self):
        #获取从lineEdit_3的输入的内容
        self.global_var_in_medicine = self.lineEdit_3.text()
        QMessageBox.information(self,'提示','获取成功！',QMessageBox.Ok,QMessageBox.Ok)
        return self.global_var_in_medicine
    
    def plot_it_in_medicine(self):
        self.pushButton_8.setEnabled(False)
        robjects.r('''ev <- eventTable(amount.units="mg", time.units="hours") %>%
    add.dosing(dose=600, nbr.doses=10, dosing.interval=24) %>%
    add.dosing(dose=2000, nbr.doses=5,
               start.time=240,dosing.interval=48) %>%
    add.sampling(0:480);''')
        robjects.r('''library(gridExtra)
library(RxODE)
library(MASS)
library(data.table)
library(ggforce)
library(ggplot2)
library(nlmixr)
library(xpose)
library(xpose.nlmixr)
library(shinyMixR)
library(stats)''')
        # print("library loaded")
        robjects.r('''sim.%s <- simulate(%s, events=ev, nSub=500)''' %(self.global_var_in_medicine, self.global_var_in_medicine))
        print("sim ok")
        robjects.r('''sim.%s.unc <- simulate(%s, events=ev, nSub=500, nStud=100)''' %(self.global_var_in_medicine, self.global_var_in_medicine))
        # print('sim unc ok')
        # pdf("fig3_%s.pdf" %self.global_var_in_medicine, width=8,height=8)
        # print("pdf ok")
        # plot(sim_unc)
        # print("sim_unc ok")
        # dev_off()
        # print("dev_off ok")
        
        robjects.r('''pdf("fig3_%s.pdf",width=8,height=8)
print(plot(sim.%s.unc))
dev.off()'''%(self.global_var_in_medicine, self.global_var_in_medicine))
        self.pushButton_8.setEnabled(True)
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)
        
class DisplayMainWin(Fit, VisualPlot, CheckVpc, MedicinePlot):
    def __init__(self):
        super().__init__()

if __name__ == "__main__":
    
    app = QApplication(sys.argv)
    win = DisplayMainWin()
    win.show()
    sys.exit(app.exec_())
